
import Taro, { request } from '@tarojs/taro';
import keys from "../constants/key";
import _startWith from 'lodash/startsWith'
import config from "../constants/config";

let token;

const baseRequest = (url, options, loading = true) => {

  try {
    token = Taro.getStorageSync(keys.TOKEN);
  }catch (e) {}
  return new Promise((resolve, reject) => {
    loading && Taro.showLoading({title: '加载中,请稍后...', mask: true})
    request({
      method: "GET",
      mode: "cors",
      retryTimes: 3,
      timeout: 8000,
      ...options,
      header: {
        'Content-Type': 'application/json',
        ...(token ? {Authorization: token} : {}),
        ...options?.header
      },
      url: _startWith('http') ? url : config.baseUrl + url,
      fail: (e) => {
        console.log(`---------> fail: e:`, e)
        reject(e)
      }
    }).then(
      response => {
        loading && Taro.hideLoading()
        resolve(response?.data ?? response);
      },
      err => {
        loading && Taro.hideLoading();
        reject(err);
      },
    )
  }).catch((e) => {
    console.log(`---> : e:`, e)
  })
};


const get = async (url, options) => {
  return baseRequest(url, options)
};

const post = async (url, options) => {
  return baseRequest(url, {
    ...options,
    method: "POST"
  })
};

const put = async (url, options) => {
  return baseRequest(url, {
    ...options,
    method: 'PUT'
  })
};

const delRequest = async (url, options) => {
  return baseRequest(url, {
    ...options,
    method: 'DELETE'
  })
}

export {
  get, post, put, delRequest
}

